package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"shejiao/base"
	user2 "shejiao/common/model/user"
	user3 "shejiao/common/service/user"
	common2 "shejiao/pkg/common"
	"shejiao/pkg/jigou"
	"shejiao/pkg/sdk/wx_app"
	"shejiao/pkg/util"
)

var AuthHandle = new(authHandel)

type authHandel struct{}

// @summary 登录
// @tags 用户接口
// @Param code query string true "code"
// @Router /api/user/auth/login [post]
func (*authHandel) Login(c *gin.Context) {
	var req struct {
		Code string `json:"code"`
	}
	err := c.ShouldBind(&req)
	if err != nil {
		common2.Response.Error(c, "缺少code", gin.H{})
		return
	}

	// 请求授权信息
	wc := base.Config.App
	response, v := wx_app.Jscode2session(wc.WxAppid, wc.Secret, req.Code)
	if response.Openid == "" {
		common2.Response.Error(c, "注册失败", gin.H{"res": response, "v": string(v), "conf": wc})
		return
	}

	var ua user2.UserAuth
	var ui user2.UserInfo
	var ut user2.UserToken
	// 查看是否注册，如果没有注册则注册
	ua, ui, ut = user3.AuthService.Get(response.Openid)
	if ua.Id == 0 {
		ua, ui, ut, err = user3.AuthService.Register(response.Openid)
		if err != nil {
			common2.Response.Error(c, "注册用户资源信息失败", gin.H{})
			return
		}
	}

	// 登录token
	appkey := base.Config.App.AuthKey
	token := util.EncodeToken(appkey, ua.Id, "user", "")

	// 即构token
	jg := base.Config.Other.Jigou

	// 结果返回
	authInfo := gin.H{"user_id": ua.Id, "is_register": ua.IsRegister}
	httpResponse := gin.H{"auth": authInfo, "user_info": ui, "user_token": ut, "token": token, "jigou": gin.H{
		"token": jigou.CreateToken(jg.Appid, jg.ServerSecret, fmt.Sprintf("%d", ua.Id)),
	}}
	common2.Response.Success(c, httpResponse)
}

// @summary 完善个人信息
// @tags 授权接口
// @Accept  json
// @Produce json
// @Param token header string true "认证token"
// @Param gender query int true "1男2女"
// @Param age query int true "年纪"
// @Param nickname query string true "昵称"
// @Param header query string true "头像"
// @Param sign query string true "个性签名"
// @Param birthday_year query int true "生日-年"
// @Param birthday_month query int true "生日-月"
// @Param birthday_day query int true "生日-日"
// @Param province query string true "省"
// @Param city query string true "市"
// @Param county query string true "县"
// @Router /api/user/auth/update_info [post]
func (*authHandel) UpdateInfo(c *gin.Context) {
	var req struct {
		Gender        int64  `json:"gender"`         // 1男2女
		Age           int64  `json:"age"`            // 年龄
		Nickname      string `json:"nickname"`       // 昵称
		Header        string `json:"header"`         // 头像
		Sign          string `json:"sign"`           // 个性签名
		BirthdayYear  int64  `json:"birthday_year"`  // 生日 年
		BirthdayMonth int64  `json:"birthday_month"` // 生日 月
		BirthdayDay   int64  `json:"birthday_day"`   // 生日 日
		Province      string `json:"province"`       // 省份
		City          string `json:"city"`           // 市
		County        string `json:"county"`         // 县
	}
	err := c.ShouldBind(&req)
	if err != nil {
		common2.Response.Error(c, "信息填写不完整", gin.H{})
		return
	}

	var ua user2.UserAuth
	var ui user2.UserInfo

	roleId := util.GetRoleId(c)

	// 修改信息
	base.Mysql.Find(&ua, "id = ?", roleId)
	if ua.Id == 0 {
		common2.Response.Error(c, "未注册用户", gin.H{})
		return
	}

	if ua.IsRegister == 1 {
		common2.Response.Error(c, "用户信息以填写", gin.H{})
		return
	}
	err = base.Mysql.Model(&ui).Where("user_id = ?", roleId).Updates(map[string]interface{}{
		"gender":         req.Gender,
		"age":            req.Age,
		"nickname":       req.Nickname,
		"header":         req.Header,
		"sign":           req.Sign,
		"birthday_year":  req.BirthdayYear,
		"birthday_month": req.BirthdayMonth,
		"birthday_day":   req.BirthdayDay,
		"province":       req.Province,
		"city":           req.City,
		"county":         req.County,
	}).Error

	if err != nil {
		common2.Response.Error(c, err.Error(), gin.H{})
		return
	}

	err = base.Mysql.Model(&ua).Where("id = ?", roleId).Updates(map[string]interface{}{"is_register": 1}).Error
	fmt.Println("err", err)
	common2.Response.Success(c, gin.H{})
}

// @summary 获取个人信息
// @tags 授权接口
// @Param token header string true "认证token"
// @Router /api/user/auth/info [post]
func (*authHandel) Info(c *gin.Context) {
	roleId := util.GetRoleId(c)

	var ua user2.UserAuth
	var ui user2.UserInfo
	var ut user2.UserToken
	// 查看是否注册，如果没有注册则注册
	ua, ui, ut = user3.AuthService.GetById(roleId)

	appkey := base.Config.App.AuthKey
	token := util.EncodeToken(appkey, ua.Id, "user", "")

	// 结果返回
	authInfo := gin.H{"user_id": ua.Id, "is_register": ua.IsRegister}
	httpResponse := gin.H{"auth": authInfo, "user_info": ui, "user_token": ut, "token": token}
	common2.Response.Success(c, httpResponse)
}
